// pages/feedback/feedback.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    content: '',
    contentLength: 0,
    images: [],
    userInfo: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.checkUserInfo();
  },

  // 检查用户信息
  async checkUserInfo() {
    const user = wx.getStorageSync('user');
    if (!user) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/my/login/login'
            });
          }, 1500);
        }
      });
      return;
    }

    const db = wx.cloud.database();
    const userInfo = await db.collection('zyzl_userList').where({
      user: user
    }).get();

    if (userInfo.data.length > 0) {
      this.setData({
        userInfo: userInfo.data[0]
      });

      // 检查是否有电话号码
      if (!userInfo.data[0].phone) {
        wx.showModal({
          title: '提示',
          content: '请先完善个人信息',
          success: (res) => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/my/information/information'
              });
            }
          }
        });
      }
    }
  },

  // 输入反馈内容
  inputContent(e) {
    const content = e.detail.value;
    this.setData({
      content,
      contentLength: content.length
    });
  },

  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 3 - this.data.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          images: [...this.data.images, ...res.tempFilePaths]
        });
      }
    });
  },

  // 预览图片
  previewImage(e) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: this.data.images,
      current: url
    });
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.images;
    images.splice(index, 1);
    this.setData({ images });
  },

  // 提交反馈
  async submitFeedback() {
    if (!this.data.userInfo || !this.data.userInfo.phone) {
      wx.showModal({
        title: '提示',
        content: '请先完善个人信息',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/my/information/information'
            });
          }
        }
      });
      return;
    }

    if (!this.data.content.trim()) {
      wx.showToast({
        title: '请输入反馈内容',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '提交中...'
    });

    try {
      let fileList = [];
      
      if (this.data.images.length > 0) {
        try {
          fileList = await Promise.all(
            this.data.images.map(async (filePath, index) => {
              try {
                const cloudPath = `complain/${this.data.userInfo.user}_${Date.now()}_${index}.png`;
                console.log('准备上传图片到路径:', cloudPath);
                
                const res = await wx.cloud.uploadFile({
                  cloudPath,
                  filePath
                });
                
                console.log('图片上传成功，fileID:', res.fileID);
                return res.fileID;
              } catch (uploadErr) {
                console.error('单张图片上传失败:', uploadErr);
                // 返回空字符串，稍后过滤掉
                return '';
              }
            })
          );
          
          // 过滤掉上传失败的图片
          fileList = fileList.filter(fileID => fileID !== '');
          console.log('所有:', fileList);
        } catch (uploadError) {
          console.error('出错:', uploadError);
          // 如果上传过程出错，继续提交文字反馈
          fileList = [];
        }
      }

      // 构建要保存的数据对象
      const feedbackData = {
        content: this.data.content,
        images: fileList,
        user: this.data.userInfo.user,
        phone: this.data.userInfo.phone,
        createTime: wx.cloud.database().serverDate()
      };
      

      // 保存反馈信息到数据库
      const db = wx.cloud.database();
      const result = await db.collection('zyzl_complain').add({
        data: feedbackData
      });
      
      console.log('反馈数据保存成功，结果:', result);

      wx.hideLoading();
      
      // 显示成功提示并立即返回
      wx.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 1500,  // 显示1.5秒
        complete: () => {
          // Toast显示完成后返回
          wx.navigateBack({
            delta: 1
          });
        }
      });

    } catch (error) {
      console.error('提交反馈失败：', error);
      wx.hideLoading();
      
      // 尝试不带图片提交
      try {
        const feedbackDataNoImages = {
          content: this.data.content,
          images: [],
          user: this.data.userInfo.user,
          phone: this.data.userInfo.phone,
          createTime: wx.cloud.database().serverDate()
        };
        
        console.log('尝试不带图片提交反馈数据:', feedbackDataNoImages);
        
        const db = wx.cloud.database();
        const result = await db.collection('zyzl_complain').add({
          data: feedbackDataNoImages
        });
        
        console.log('不带图片的反馈数据保存成功，结果:', result);
        
        // 在不带图片提交成功的情况下也立即返回
        wx.showToast({
          title: '提交成功(无图片)',
          icon: 'success'
        });
        
        wx.navigateBack({
          delta: 1
        });
      } catch (finalError) {
        console.error('最终提交失败:', finalError);
        wx.showToast({
          title: '提交失败，请稍后重试',
          icon: 'none'
        });
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})